<template>
  <el-card shadow="hover">
    <!-- 添加商品的按钮 -->
    <el-button type="primary" size="default" :icon="Plus" @click="addTradeMark">
      添加品牌
    </el-button>
    <el-badge
      :value="tradeMarkArr.length"
      class="item"
      type="primary"
      style="margin: 0 20px"
    >
      <el-button :icon="Download" type="primary" size="default" @click="handler"
        >到处此页数据</el-button
      >
    </el-badge>
    <!-- 表格 -->
    <el-table border style="margin: 10px 0px" :data="tradeMarkArr">
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="updateTradeMark(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定要删除${row.tmName}?`"
            width="200px"
            @click="deletaTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- page-sizes存储的是显示每页的数据 -->
    <!-- background boolean类型的是否显示背景颜色 -->
    <!-- layout 组件布局 -->
    <!-- total 总共多少条数据 -->
    <el-pagination
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      background
      :page-sizes="[3, 5, 7, 9]"
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :prev-icon="ArrowLeftBold"
      :next-icon="ArrowRightBold"
      @current-change="getHasTradeMark"
      @size-change="sizeHandler"
    />
  </el-card>

  <!-- 对话框 -->
  <el-dialog
    v-model="dialogVisite"
    style="margin-top: 100px"
    :title="trademarkParams.id ? '修改成功' : '添加品牌'"
    visible
  >
    <!-- 表单数据       :rules="rules" -->
    <el-form
      ref="form"
      label-width="100px"
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
    >
      <!-- 第一个输入框 -->
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <!-- 点击的按钮 -->
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <!-- upload 里面的action是发送请求 -->
        <el-upload
          class="avatar-uploader"
          action="/app-dev/admin/product/fileUpload"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// 导入的是icon的图标库
import {
  Plus,
  Download,
  ArrowRightBold,
  ArrowLeftBold,
  Delete,
  Edit,
} from "@element-plus/icons-vue";

import { ref, onMounted, reactive, nextTick } from "vue";

// 导入组件样式
import { ElMessage } from "element-plus";

// 获取已有品牌
import {
  reqTradeMarkList,
  reqAddorUpdateTradeMark,
  reqRemoveTradeMark,
} from "@/api/product/trademark";
import type { TradeMark, Records } from "@/api/product/trademark/type";

// 导入excel插件对象
import * as XLSX from "xlsx";

// 分页器  当前所在的页面
const pageNo = ref<number>(1);
// 当前页面显示的数据
const pageSize = ref<number>(3);

// 创建el-from
const form = ref<any>();

// 存储全部已有的数据
let tradeMarkArr = ref<Records>([]);
// 存储的是全部数据的条数
let total = ref<number>(0);

// 控制的是会话框 默认为不显示
let dialogVisite = ref<boolean>(false);


// 收集表单数据
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});

// 获取已有的数据
const getHasTradeMark = async (page: number = 1) => {
  // 存储当前页码
  pageNo.value = page;
  // 发送请求
  const result = await reqTradeMarkList(pageNo.value, pageSize.value);
  // 存储数据
  tradeMarkArr.value = result.records;
  // 存储多少条数据
  total.value = result.total;
};

// 生命周期挂载
onMounted(() => {
  // 发送请求
  getHasTradeMark();
});

// 分页器下拉菜单回调函数
const sizeHandler = (limit: number) => {
  // 存储当前页面显示的数据
  pageSize.value = limit;
  // 发送请求
  getHasTradeMark();
};

// 控制的是当前页面显不显示对话框
const addTradeMark = () => {
  // 控制对话框是否显示
  dialogVisite.value = true;
  // 延迟的加载
  nextTick(() => {
    form.value.clearValidate("tamName");
    form.value.clearValidate("logoUrl");
  });
  // 清空数据
  reset();
};
// 文件上传成功的钩子
const handleAvatarSuccess = (response: any, uploadFile: any) => {
  //
  trademarkParams.logoUrl = response.data;
  // 进行的是表单的验证
  form.value.clearValidate("logoUrl");
};
// 图片成功上传之前触发的
const beforeAvatarUpload = (rawFile: any) => {
  // 判断用户传送的图片
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 8) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "你传的图片的大小大于2MB!",
      });
      return false;
    }
  } else {
    ElMessage.error({
      type: "error",
      message: "你传的类型有误",
    });
    return false;
  }
};

// 确定的回调
const confirm = async () => {
  // 发送请求之前进行表单的验证
  await form.value?.validate();
  // 判断
  try {
    // 发送请求
    await reqAddorUpdateTradeMark(trademarkParams);
    // 提示信息
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改成功" : "添加成功",
    });
    // 对话框关闭
    dialogVisite.value = false;
    // 添加成功后需要重新获取信息
    getHasTradeMark(trademarkParams.id ? pageNo.value : 1);
  } catch (error) {
    // 提示信息
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 点击取消的回调函数
const cancel = () => {
  dialogVisite.value = false;
};

// 清空的回调函数
const reset = () => {
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
};
// 更新成功的回调
const updateTradeMark = (row: TradeMark) => {
  dialogVisite.value = true;
  // 收集更新的参数
  Object.assign(trademarkParams, row);

  // 进行延迟的加载
  nextTick(() => {
    form.value.clearValidate("tmName");
    form.value.clearValidate("logoUrl");
  });
};
// 进行品牌名称的验证
const validatoeTmName = (rule: any, value: any, callBack: any) => {
  if (value.length >= 2) {
    callBack();
  } else {
    callBack(new Error("品牌名称至少要两个字"));
  }
};
// 进行品牌Logo图片校验-点击确定进行校验
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value.length) {
    callBack();
  } else {
    callBack(new Error("请上传品牌logo"));
  }
};
const rules = {
  tmName: [{ reactive: true, trigger: "blur", validator: validatoeTmName }],
  logoUrl: [{ reactive: true, validator: validatorLogoUrl }],
};
// 删除已有的品牌
const deletaTradeMark = async (id: number) => {
  try {
    // 发送请求
    await reqRemoveTradeMark(id);
    // 提示信息
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    // 再次重新发送请求
    getHasTradeMark(pageNo.value);
  } catch (error) {
    // 删除失败的提示信息
    ElMessage({
      type: "error",
      message: "删除成功",
    });
  }
};
// 生成elcel
const handler = () => {
  //把你的JSON数据格式编程excel插件人家需要数据格式
  const worksheet = XLSX.utils.json_to_sheet(tradeMarkArr.value);
  //插件需要生成excel文件容器对象
  const workbook = XLSX.utils.book_new();
  //准备生成文件
  XLSX.utils.book_append_sheet(workbook, worksheet, "Dates");
  //生成文件
  XLSX.writeFile(workbook, "Data.xlsx");
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
